import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cartItems: [
      { id: 1, name: '手机', price: 1000, quantity: 1 },
      { id: 2, name: '电脑', price: 2000, quantity: 1 },
      { id: 3, name: '键盘', price: 200, quantity: 2 }
    ]
  },
  mutations: {
    ADD_ITEM(state, item) {
      const existingItem = state.cartItems.find(i => i.id === item.id)
      if (existingItem) {
        existingItem.quantity++
      } else {
        state.cartItems.push({ ...item, quantity: 1 })
      }
    },
    REMOVE_ITEM(state, itemId) {
      const index = state.cartItems.findIndex(item => item.id === itemId)
      if (index !== -1) {
        state.cartItems.splice(index, 1)
      }
    },
    INCREMENT_QUANTITY(state, itemId) {
      const item = state.cartItems.find(i => i.id === itemId)
      if (item) {
        item.quantity++
      }
    },
    DECREMENT_QUANTITY(state, itemId) {
      const item = state.cartItems.find(i => i.id === itemId)
      if (item && item.quantity > 1) {
        item.quantity--
      }
    }
  },
  actions: {
    addItem({ commit }, item) {
      commit('ADD_ITEM', item)
    },
    removeItem({ commit }, itemId) {
      commit('REMOVE_ITEM', itemId)
    },
    incrementQuantity({ commit }, itemId) {
      commit('INCREMENT_QUANTITY', itemId)
    },
    decrementQuantity({ commit }, itemId) {
      commit('DECREMENT_QUANTITY', itemId)
    }
  },
  getters: {
    totalPrice: state => {
      return state.cartItems.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    }
  }
})